﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using AvailableRooms.Exchange;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;

namespace AvailableRooms
{
    public partial class Form1 : Form
    {
        private ExchangeService _ExchangeService;

        private List<EmailAddressType> _RoomLists;
        private List<RoomType> _Rooms;
        private List<TimeZoneDefinitionType> _TimeZones;
        private List<CalendarEvent> _Appointments;

        private SerializableTimeZone _TimeZone;
        private FreeBusyViewOptionsType _FreeBusyViewOptions;

        #region TextBox Values

        public string Username
        {
            get { return tbUsername.Text.Split('\\')[1]; }
        }

        public string Domain
        {
            get { return tbUsername.Text.Split('\\')[0]; }
        }

        public string Password
        {
            get { return tbPassword.Text; }
        }
        
        public string ExchangeUrl
        {
            get { return cbExchangeServer.SelectedItem.ToString(); }
        }
        
        #endregion

        public Form1()
        {
            InitializeComponent();

            this.cbExchangeServer.SelectedIndex = 0;
            this.cbExchangeServer.SelectedIndexChanged += new System.EventHandler(this.cbExchangeServer_SelectedIndexChanged);

            InitializeExchangeService();

            InitializeTimeZone();

            InitializeViewOptions();
        }

        private void InitializeViewOptions()
        {
            _FreeBusyViewOptions = new FreeBusyViewOptionsType();

            _FreeBusyViewOptions.TimeWindow = new Duration();
            _FreeBusyViewOptions.TimeWindow.StartTime = DateTime.Today;
            _FreeBusyViewOptions.TimeWindow.EndTime = DateTime.Today.AddDays(1);
            _FreeBusyViewOptions.RequestedView = FreeBusyViewType.DetailedMerged;
            _FreeBusyViewOptions.RequestedViewSpecified = true;
            _FreeBusyViewOptions.MergedFreeBusyIntervalInMinutes = 30;
            _FreeBusyViewOptions.MergedFreeBusyIntervalInMinutesSpecified = true;
        }

        private void InitializeTimeZone()
        {
            _TimeZone = new SerializableTimeZone();

            // Set Base UTC
            _TimeZone.Bias = -60;

            // Set Standerd Time
            _TimeZone.StandardTime = new SerializableTimeZoneTime();
            _TimeZone.StandardTime.Bias = 0;
            _TimeZone.StandardTime.Time = "02:00:00";
            _TimeZone.StandardTime.DayOrder = 5;
            _TimeZone.StandardTime.Month = 10;
            _TimeZone.StandardTime.DayOfWeek = DayOfWeek.Sunday.ToString();

            // Set Daylight Time
            _TimeZone.DaylightTime = new SerializableTimeZoneTime();
            _TimeZone.DaylightTime.Bias = 0;
            _TimeZone.DaylightTime.Time = "02:00:00";
            _TimeZone.DaylightTime.DayOrder = 5;
            _TimeZone.DaylightTime.Month = 3;
            _TimeZone.DaylightTime.DayOfWeek = DayOfWeek.Sunday.ToString();
        }

        private void InitializeExchangeService()
        {
            // Initialize the ExchangeService
            _ExchangeService = new ExchangeService();

            // Specify the Exchange Server version
            _ExchangeService.RequestServerVersionValue = new RequestServerVersion();
            _ExchangeService.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2010_SP1;

            // Set the Credentails
            _ExchangeService.Credentials = new NetworkCredential(Username, Password, Domain);

            // Set Exchange Server Url
            _ExchangeService.Url = ExchangeUrl;
        }

        private void LoadRoomLists()
        {
            // Load Room Lists
            _RoomLists = _ExchangeService.GetRoomLists();

            // Bind Room Lists
            comboBox1.DataSource = (from roomLists in _RoomLists
                                    select roomLists.Name).ToList();
        }

        private void LoadRooms()
        {
            // Load Rooms
            _Rooms = _ExchangeService.GetRooms(_RoomLists[comboBox1.SelectedIndex]);

            // Bind Rooms
            comboBox2.DataSource = (from room in _Rooms
                                    select room.Id.Name).ToList();
        }

        private void LoadRoomSchedule()
        {
            List<MailboxData> mailBoxes = new List<MailboxData>();

            mailBoxes.Add(new MailboxData() { AttendeeType = MeetingAttendeeType.Required, Email = new EmailAddress() { Address = _Rooms[comboBox2.SelectedIndex].Id.EmailAddress, Name = _Rooms[comboBox2.SelectedIndex].Id.Name }, ExcludeConflicts = false });

            _Appointments = _ExchangeService.GetRoomAvailability(mailBoxes, _TimeZone, _FreeBusyViewOptions);
            
            dataGridView1.DataSource = (from appointment in _Appointments
                                        select new
                                            {
                                                Busy = appointment.BusyType.ToString(),
                                                StartTime = appointment.StartTime.ToShortTimeString(),
                                                EndTime = appointment.EndTime.ToShortTimeString(),
                                            }).ToList();
        }

        private void LoadTimeZones()
        {
            _TimeZones = _ExchangeService.GetServerTimeZones();

            comboBox3.DataSource = (from timeZone in _TimeZones
                                    select timeZone.Name).ToList();
        }

        #region Events

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadRooms();
        }

        private void cbExchangeServer_SelectedIndexChanged(object sender, EventArgs e)
        {
            _ExchangeService.Url = ExchangeUrl;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            LoadRoomLists();
            LoadTimeZones();
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadRoomSchedule();
        }

        #endregion
    }
}